import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.util.Observable;
import java.util.Random;

/**
 * @author leejun.happy@gmail.com
 * @date 2017年7月17日 上午11:06:47
 * @describe
 */

public class Tank extends Observable implements Runnable {

	public static boolean running = true; // 运行状态
	public static boolean paused = false;
	
	boolean good = true;
	boolean live = true;

	public static final int SPEED = 5;
	public static final int WIDTH = 30;
	public static final int HEIGHT = 30;
	
	Direction dir = Direction.STOP;
	Direction ptDir = Direction.D;
	
	public Tank() {
	}

	public Tank(int x, int y) {
		this.x = x;
		this.y = y;
	}

	public Direction getDir() {
		return dir;
	}

	public void setDir(Direction dir) {
		this.dir = dir;
	}

	public int x = 10, y = 10;
	
	@Override
	public void run() {
		running = true;
		while (running) {
			try {
				Thread.sleep(1000 / 60);
			} catch (Exception e) {
				break;
			}
			if (!paused) {
				move();
				setChanged(); // Model通知View数据已经更新
				notifyObservers();
			}
			
		}
		running = false;
	}
	
	void draw(Graphics g) {
		if (!this.live) {
			return;
		}
		
		if (this.good) {
			g.setColor(Color.RED);
		} else {
			g.setColor(Color.BLUE);
		}
		
		g.fillRect(x, y, 30, 30);
		
		g.setColor(Color.BLACK);
		switch(this.ptDir) {
		case L:
			g.drawLine(x, y + HEIGHT/2, x + WIDTH/2, y + HEIGHT/2);
			break;
		case U:
			g.drawLine(x + WIDTH/2, y, x + WIDTH/2, y + HEIGHT/2);
			break;
		case R:
			g.drawLine(x + WIDTH, y + HEIGHT/2, x + WIDTH/2, y + HEIGHT/2);
			break;
		case D:
			g.drawLine(x + WIDTH/2, y + HEIGHT, x + WIDTH/2, y + HEIGHT/2);
			break;
		default:
			break;
		}
	}

	void move() {
		if (!this.good) {
			int randonInt = new Random().nextInt(100);
			if (randonInt > 90) {
				Direction[] dirs = Direction.values();
				this.dir = dirs[new Random().nextInt(dirs.length)];
			}
		}
		
		switch (this.dir) {
		case D:
			y += SPEED;
			break;
		case L:
			x -= SPEED;
			break;
		case U:
			y -= SPEED;
			break;
		case R:
			x += SPEED;
			break;
		case STOP:	
		default:
			break;
		}
		
		if (this.x < 0) {
			this.x = 0;
		}
		
		if (this.y < 0) {
			this.y = 0;
		}
		
		if (this.x + WIDTH > TankView.WIDTH) {
			this.x = TankView.WIDTH - WIDTH;
		}
		
		if (this.y + HEIGHT > TankView.HEIGHT) {
			this.y = TankView.HEIGHT - HEIGHT;
		}
		
		if (this.dir != Direction.STOP) {
			this.ptDir = this.dir;
		}
			
	}
	
	public void fire() {
		if (!this.live) {
			return;
		}
		int x = this.x + WIDTH/2 - Shell.WIDTH/2;
		int y = this.y + HEIGHT/2 - Shell.HEIGHT/2;
		Shell shell =  new Shell(x, y, this.ptDir);
		shell.good = this.good;
		TankControl.shells.add(shell);
	}
	
	public Rectangle getRectangel() {
		return new Rectangle(x, y, WIDTH, HEIGHT);
	}
	
}
